import 'dart:async';

import 'package:aliplayer_widget/aliplayer_widget_lib.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/discover_topic_entity.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/following_moment_dto_entity.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/following_user_list_dto_entity.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/moment_entity.dart';
import 'package:gameplay_flutter/lib_network/http_api.dart';
import 'package:gameplay_flutter/lib_network/http_helper.dart';
import 'package:gameplay_flutter/lib_runtime/event_bus.dart';
import 'package:get/get.dart';

import '../../lib_im/index.dart';
import '../../lib_runtime/event_center.dart';
import '../../lib_runtime/event_constant.dart';

class DiscoverHomeLogic extends GetxController {
  var topics = <DiscoverTopicEntity>[].obs;
  var moments = <MomentEntity>[].obs;
  var followMoments = <MomentEntity>[].obs;
  var followingUsers = <FriendModel>[].obs;

  var currentTopic = DiscoverTopicEntity().obs;

  StreamSubscription? _eventSub;
  StreamSubscription? _eventSub2;
  StreamSubscription? _eventSub3;
  StreamSubscription? _eventSub0;

  final refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  @override
  void onInit() async {
    FlutterAliPlayerGlobalSettings.setGlobalEnvironment(2);
    discoverRecommendList();
    followList();
    discoverFollowingDynamicList();

    _eventSub0 = eventBus.on<UpdateDiscoverAction>().listen((event) {
      discoverRecommendList();
      followList();
      discoverFollowingDynamicList(showLoading: false);
    });

    _eventSub = eventBus.on<FollowUserAction>().listen((event) {
      followList();
      discoverFollowingDynamicList(showLoading: false);
    });

    _eventSub2 = eventBus.on<LikeAction>().listen((event) {
      var i = moments.indexWhere((element) => element.id == event.moment.id);
      if (i >= 0) {
        moments[i] = moments[i]
          ..likes = event.moment.likes
          ..isLike = true;
      }
    });

    _eventSub3 = eventBus.on<UnLikeAction>().listen((event) {
      var i = moments.indexWhere((element) => element.id == event.moment.id);
      if (i >= 0) {
        moments[i] = moments[i]
          ..likes = event.moment.likes
          ..isLike = false;
      }
    });

    super.onInit();
  }

  @override
  onClose() {
    _eventSub0?.cancel();
    _eventSub?.cancel();
    _eventSub2?.cancel();
    _eventSub3?.cancel();
    super.onClose();
  }

  discoverRecommendList() async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverRecommendList,
      showLoading: true,
      showToast: true,
    );
    debugPrint("res.result: ${res.result["topics"]}");
    topics.assignAll((res.result["topics"] as List).map((e) => DiscoverTopicEntity.fromJson(e)));
    if (topics.isNotEmpty) currentTopic(topics.first);
    discoverProductFlow();
  }

  var momentPageNum = 1;

  discoverProductFlow({int? dynamicId, bool load = false, bool showLoading = true}) async {
    if (load) {
      momentPageNum += 1;
    } else {
      momentPageNum = 1;
    }
    var res = await HttpHelper.instance().post(
      HttpApi.discoverProductFlow,
      body: {
        "flowTypes": 5,
        // if (currentTopic().id != 0) "topicId": currentTopic().id,
        "pageNum": momentPageNum,
        "pageSize": 10,
        "dynamicId": dynamicId
      },
      showLoading: showLoading,
      showToast: true,
    );
    if (load) {
      moments.addAll((res.result as List).map((e) => MomentEntity.fromJson(e)));
    } else {
      moments.assignAll((res.result as List).map((e) => MomentEntity.fromJson(e)));
    }
  }

  // 关注列表
  followList({
    showLoading = false,
    int pageNum = 1,
    int pageSize = 20,
    int type = 0, //0:全部 1:在线
  }) async {
    final resp = await HttpHelper.instance().post(
      '/api/v1/user-friend/get-attentions',
      showLoading: showLoading,
      showToast: true,
      body: {
        'type': type,
        'pageNum': pageNum,
        'pageSize': pageSize,
      },
    );
    if (!resp.isSuccess || resp.result is! Map) return [];
    if (resp.result['list'] is! List) return [];
    var list = List.generate(
      resp.result['list'].length,
      (index) => FriendModel.fromJson(resp.result['list'][index]),
    );
    followingUsers.assignAll(list);
  }

  var followingMomentPageNum = 1;

  discoverFollowingDynamicList({bool load = false, bool showLoading = true}) async {
    if (load) {
      followingMomentPageNum += 1;
    } else {
      followingMomentPageNum = 1;
    }
    var res = await HttpHelper.instance().post(
      HttpApi.discoverFollowingDynamicList,
      body: {"type": 5, "pageNum": followingMomentPageNum, "pageSize": 10},
      showLoading: showLoading,
      showToast: true,
    );

    var dto = FollowingMomentDtoEntity.fromJson(res.result);
    // print('res.result 的类型: ${res.result.runtimeType}');
    // print('res.result 的内容: $res.result');

    if (load) {
      followMoments.addAll(dto.dynamicList.map((e) => e.dynamicVO));
    } else {
      followMoments.assignAll(dto.dynamicList.map((e) => e.dynamicVO));
    }
  }
}
